package com.example.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.auth.consts.IndexConst;
import com.example.auth.entity.SysMenu;
import com.example.auth.entity.SysUser;
import com.example.auth.exception.LyException;
import com.example.auth.service.SysMenuService;
import com.example.auth.service.SysUserService;
import com.example.auth.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 李某人
 * @Date 2023/7/22 22:09
 * @Version 1.0
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String username)  {
        var wrapper = new LambdaQueryWrapper<SysUser>();
        wrapper.eq(SysUser::getUsername,username);
        var sysUser = sysUserService.getOne(wrapper);
        if(sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        if(sysUser.getStatus() == 0){
            throw new RuntimeException("用户被禁用了");
        }
        List<String> userPermsList = new ArrayList<>();
        if(sysUser.getId() == 1){
            List<SysMenu> sysMenuList = sysMenuService.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getStatus, IndexConst.STATUS_OPEN));
            userPermsList = sysMenuList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
        }else {
            userPermsList = sysMenuService.findUserPermsList(sysUser.getId());
        }
        userPermsList=userPermsList.stream().filter(string -> !StringUtils.isEmpty(string)).collect(Collectors.toList());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String perm : userPermsList) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }
        //保存权限
        redisUtil.set(sysUser.getUsername(), JSON.toJSONString(authorities));
        return new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
    }
}
